package com.melon.web;

import com.melon.domain.GeneralObjectResp;
import com.melon.entity.admin.User;
import com.melon.service.RedisService;
import com.melon.service.UserService;
import com.melon.utils.GSON;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * Created by zhiqi.shao on 2017/3/14.
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;


    @RequestMapping("/loginIndex")
    public String loginIndex(){
        return "admin/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(User user,HttpSession httpSession){
        log.info("请求报文: {}", GSON.toJson(user));
        User u=userService.findUserByNamePswd(user.getUsername(),user.getPassword());
        if(u!=null){
            redisService.set(httpSession.getId(), u,60L);
            return GeneralObjectResp.success(null);
        }
        return GeneralObjectResp.failure("用户名或密码错误");
    }


    @RequestMapping("/registIndex")
    public String registIndex(){
        return "admin/register";
    }


    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    @ResponseBody
    public Object regist(User user){
        log.info("请求报文: {}", GSON.toJson(user));
        User u=userService.save(user);
        if(u!=null){
            return GeneralObjectResp.success(null);
        }
        return GeneralObjectResp.failure("保存失败");
    }


    @RequestMapping("/adminIndex")
    public String adminIndex(Model model, HttpSession httpSession){
        Object user=redisService.get(httpSession.getId());
        if(user==null){
            return "admin/login";
        }
        User u=GSON.fromJson(GSON.toJson(user),User.class);
        model.addAttribute("user",u);
        return "admin/adminIndex";
    }

    @RequestMapping("/adminOut")
    public String adminLoginout( HttpSession httpSession){
        redisService.remove(httpSession.getId());
        return "admin/login";
    }


    @RequestMapping("/adminCheck")
    public String adminCheck(){
        return "admin/adminCheck";
    }

    @RequestMapping("/test")
    @ResponseBody
    public User test(Long id){
        User user= userService.getUser(id);
        log.info(GSON.toJson(user));
        return user;
    }

    @RequestMapping("show")
    public Object show(HttpServletRequest request) {
        return request.getSession().getAttribute("username");
    }
}
